
//
//  YYYComposeTextView.swift
//  HotNews
//
//  Created by YYY on 2017/11/9.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

//占位符label
var placeHolderLabel = UILabel(text: "分享新鲜事儿...", fontSize: 14, color: UIColor.lightGray)

class YYYComposeTextView: UITextView {
    
    override init(frame: CGRect, textContainer: NSTextContainer?)
    {
        super.init(frame: frame, textContainer: textContainer)
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(observeTextChange), name: NSNotification.Name.UITextViewTextDidChange, object: self)
        //初始化控件
        setupUI()
    }
    
    //注销通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //监听文本变化
    @objc private func observeTextChange()
    {
        placeHolderLabel.isHidden = self.hasText
    }
}

extension YYYComposeTextView
{
    //初始化控件
    func setupUI()
    {
        //设置文本属性
        font = UIFont.systemFont(ofSize: 14)
        textColor = UIColor.darkGray
        alwaysBounceVertical = true
        keyboardDismissMode = .onDrag
        
        //添加占位label
        placeHolderLabel.frame.origin = CGPoint(x: 5, y: 8)
        addSubview(placeHolderLabel)
    }
}

extension YYYComposeTextView
{
    //表情文本
    var emoticonText: String
    {
        guard let attributed = attributedText else
        {
            return ""
        }
        var result = String()
        attributed.enumerateAttributes(in: NSRange(location: 0, length: attributed.length), options: []) { (dict, range, _) in
            
            if let attachment = dict[NSAttributedStringKey.attachment] as? EmoticonTextAttachment
            {
                //表情
                result += attachment.chs ?? ""
            }
            else
            {
                //文字
                let str = (attributed.string as NSString).substring(with: range)
                result += str
            }
        }
        return result
    }
    
    //插入表情
    func insertEmoticon(em: YYYEmoticonModel?)
    {
        guard let em = em else {
            //em = nil代表删除按钮
            //向后删除
            deleteBackward()
            return
        }
        //emoji字符串
        if let emoji = em.emoji,
            let textRange = selectedTextRange
        {
            //插入文本
            replace(textRange, withText: emoji)
            return
        }
        //后续处理图片表情
        let imageText = em.imageText(font: font!)
        //可变字符串
        let attributed = NSMutableAttributedString(attributedString: attributedText)
        attributed.replaceCharacters(in: selectedRange, with: imageText)
        
        //记录光标位置
        let range = selectedRange
        attributedText = attributed
        //恢复光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        //代理方法
        delegate?.textViewDidChange?(self)
        //通知方法
        observeTextChange()
    }
}

